package cn.opencodes.framework.tools.utils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.Gson;
/**
 * Json操作辅助类
 * @author hj
 */
public class JsonUtils {
	 /**
     * Object转成JSON数据
     */
    public static String toJson(Object object){
        if(object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String){
            return String.valueOf(object);
        }
        return  new Gson().toJson(object);
    }

    /**
     * JSON数据，转成Object
     */
    public static <T> T fromJson(String json, Class<T> clazz){
        return new Gson().fromJson(json, clazz);
    }
    
    public static <T> List<T> fromJsonList(String json, Class<T> clazz){
    	return new Gson().fromJson(json, new ParameterizedType() {
			@Override
			public Type getRawType() {
				return List.class;
			}
			@Override
			public Type[] getActualTypeArguments() {
				return new Type[]{clazz};
			}
			@Override
			public Type getOwnerType() {
				return null;
			}
		});
    }
    
}
